package 力扣._00周赛._119双周赛.问题3;

import java.util.HashMap;
import java.util.Map;

class Solution {
    public int maxSubarrayLength(int[] nums, int k) {
        //滑动窗口
        Map<Integer, Integer> map = new HashMap<>();
        int max_len = 1;
        int left = 0, right = 0; //left开，包含r
        while (right < nums.length) {

            //将当前元素(r指向的)加入
            if (map.containsKey(nums[right])) {
                int n = map.get(nums[right]);
                if (n < k)
                    map.put(nums[right], n + 1);
                else {
                    //len右移直至len-1为nums[r]
                    while (nums[left] != nums[right]) {
                        map.put(nums[left], Math.max(0, map.get(nums[left]) - 1));
                        left++;
                    }
                    left++;
                }
            } else {
                map.put(nums[right], 1);
            }
            max_len = Math.max(right - left + 1, max_len);
            right++;
        }
        return max_len;

    }

    public static void main(String[] args) {
        int[] nums = new int[]{1,2,2};
        int k = 3;
        new Solution().maxSubarrayLength(nums,k);
    }
}